package com.management.department.teacherinfosystem.Controller;

import com.management.department.teacherinfosystem.DTO.ActivityStatsDTO;
import com.management.department.teacherinfosystem.DTO.ActivitySubmitDTO;
import com.management.department.teacherinfosystem.Entity.Activity;
import com.management.department.teacherinfosystem.Entity.ActivityAttachment;
import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Repository.ActivityAttachmentRepository;
import com.management.department.teacherinfosystem.Repository.UserRepository;
import com.management.department.teacherinfosystem.Service.ActivityService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/activities")
@RequiredArgsConstructor
public class ActivityController {

    private final ActivityService activityService;
    private final UserRepository userRepository;
    private final ActivityAttachmentRepository activityAttachmentRepository;

    @Value("${file.upload.activity-dir:uploads/activity_attachments/}")
    private String activityUploadDir;

    private User getCurrentUser() {
        org.springframework.security.core.Authentication auth =
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = auth.getName();
        return userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
    }

    private boolean currentIsAdmin() {
        org.springframework.security.core.Authentication auth =
                org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
        return auth.getAuthorities().stream()
                .anyMatch(a -> {
                    String au = a.getAuthority();
                    return "ROLE_ADMIN".equalsIgnoreCase(au) || "ADMIN".equalsIgnoreCase(au);
                });
    }

	@GetMapping("/my")
	@Transactional(readOnly = true)
	public ResponseEntity<?> listMy(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "role", required = false) String role,
            @RequestParam(value = "organizerLevel", required = false) String organizerLevel,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "status", required = false) String status
    ) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        Pageable pageable = PageRequest.of(Math.max(page - 1, 0), Math.max(size, 1));
        Page<Activity> result = activityService.listMyActivities(user.getId(), pageable, type, role, organizerLevel, startDate, endDate, status);
        return ResponseEntity.ok(result);
    }

	@GetMapping("/list")
	@Transactional(readOnly = true)
	public ResponseEntity<?> listAllOrMy(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "role", required = false) String role,
            @RequestParam(value = "organizerLevel", required = false) String organizerLevel,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "status", required = false) String status
    ) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        Pageable pageable = PageRequest.of(Math.max(page - 1, 0), Math.max(size, 1));
        Page<Activity> result = currentIsAdmin()
                ? activityService.listAllActivities(pageable, type, role, organizerLevel, startDate, endDate, status)
                : activityService.listMyActivities(user.getId(), pageable, type, role, organizerLevel, startDate, endDate, status);
        return ResponseEntity.ok(result);
    }

	@GetMapping("/{id:[0-9]+}")
	@Transactional(readOnly = true)
	public ResponseEntity<?> get(@PathVariable("id") Long id) {
        Activity a = activityService.getById(id);
        if (a == null) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(a);
    }

	@PostMapping
	@Transactional
	public ResponseEntity<?> create(@RequestBody ActivitySubmitDTO dto) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        if (dto.getParticipantName() == null || dto.getParticipantName().isEmpty()) dto.setParticipantName(user.getName());
        Long id = activityService.create(user.getId(), dto);
        return ResponseEntity.ok(id);
    }

	@PutMapping("/{id:[0-9]+}")
	@Transactional
	public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody ActivitySubmitDTO dto) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        activityService.update(id, user.getId(), dto);
        return ResponseEntity.ok("更新成功");
    }

	@DeleteMapping("/{id:[0-9]+}")
	@Transactional
	public ResponseEntity<?> delete(@PathVariable("id") Long id) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        activityService.delete(id, user.getId());
        return ResponseEntity.ok("删除成功");
    }

    /* ======== 审核 / 统计（管理员） ======== */
	@PostMapping("/{id:[0-9]+}/review")
	@Transactional
	public ResponseEntity<?> review(@PathVariable("id") Long id, @RequestBody Map<String, String> payload) {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        if (!currentIsAdmin()) return ResponseEntity.status(403).body("权限不足");
        String status = payload.get("status");
        String opinion = payload.get("opinion");
        activityService.review(id, user.getId(), status, opinion);
        return ResponseEntity.ok("审核完成");
    }

	@GetMapping("/stats")
	@Transactional(readOnly = true)
	public ResponseEntity<?> stats(
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "role", required = false) String role,
            @RequestParam(value = "organizerLevel", required = false) String organizerLevel,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate
    ) {
        if (!currentIsAdmin()) return ResponseEntity.status(403).body("权限不足");
        ActivityStatsDTO dto = activityService.stats(type, role, organizerLevel, startDate, endDate);
        return ResponseEntity.ok(dto);
    }

    /* ======== 附件相关 ======== */
	@PostMapping("/{id:[0-9]+}/attachments")
	@Transactional
	public ResponseEntity<?> uploadAttachment(
            @PathVariable("id") Long id,
            @RequestParam("file") MultipartFile file,
            @RequestParam("fileType") String fileType
    ) throws Exception {
        User user = getCurrentUser();
        if (user == null) return ResponseEntity.status(401).body("用户未登录");
        Activity act = activityService.getById(id);
        if (act == null) return ResponseEntity.notFound().build();

        String base = activityUploadDir;
        if (!StringUtils.hasText(base)) base = "uploads/activity_attachments/";
        if (!base.endsWith("/") && !base.endsWith("\\")) base = base + "/";
        File dir = new File(base);
        if (!dir.exists()) dir.mkdirs();
        String ext = "";
        String original = file.getOriginalFilename();
        if (original != null && original.contains(".")) ext = original.substring(original.lastIndexOf('.'));
        String saveName = UUID.randomUUID() + ext;
        File dest = new File(base + saveName);
        file.transferTo(dest);

        ActivityAttachment att = new ActivityAttachment();
        att.setActivity(act);
        att.setFileName(original != null ? original : saveName);
        att.setFilePath(base + saveName);
        att.setFileType(fileType);
        att.setFileSize(file.getSize());
        att.setContentType(file.getContentType());
        activityAttachmentRepository.save(att);
        return ResponseEntity.ok("上传成功");
    }

	@GetMapping("/{id:[0-9]+}/attachments")
	@Transactional(readOnly = true)
	public ResponseEntity<?> listAttachments(@PathVariable("id") Long id) {
        List<ActivityAttachment> list = activityAttachmentRepository.findByActivity_Id(id);
        return ResponseEntity.ok(list);
    }

	@DeleteMapping("/attachments/{attachmentId:[0-9]+}")
	@Transactional
	public ResponseEntity<?> deleteAttachment(@PathVariable("attachmentId") Long attachmentId) {
        activityAttachmentRepository.deleteById(attachmentId);
        return ResponseEntity.ok("已删除");
    }
} 